﻿using IdentityServer;
using IdentityServer4;
using IdentityServerHost.Quickstart.UI;
using Microsoft.AspNetCore.Authentication;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;
using System.Security.Claims;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Extensions.DependencyInjection;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllersWithViews();

//添加身份认证
builder.Services.AddIdentityServer()
                #region 临时密钥，调试或开发时使用
                .AddDeveloperSigningCredential()
                #endregion

                #region X.509证书
                //生产环境推荐使用证书方式来配置签名凭证，path_to_cert.pfx
                //.AddSigningCredential(new X509Certificate2("path_to_cert.pfx", "certificate_password"))
                #endregion
                .AddInMemoryIdentityResources(Config.IdentityResources)
                .AddInMemoryApiScopes(Config.ApiScopes)
                .AddInMemoryClients(Config.Clients)
                .AddTestUsers(TestUsers.Users);


//添加授权服务
builder.Services.AddAuthentication()
                //.AddGoogle()
                .AddOpenIdConnect("oidc", "Demo IdentityServer", options =>
                {
                    options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;
                    options.SignOutScheme = IdentityServerConstants.SignoutScheme;
                    options.SaveTokens = true;

                    options.Authority = "https://demo.duendesoftware.com";
                    options.ClientId = "interactive.confidential";
                    options.ClientSecret = "secret";
                    options.ResponseType = OpenIdConnectResponseType.Code;

                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        NameClaimType = "name",
                        RoleClaimType = "role"
                    };
                })
                .AddGitee("Gitee", "Demo Gitee", options =>
                {
                    options.ClientId = "43e21bdfe93a542a8af3e44396cbe39ef0c9318c4c0bc640c354a16a7372347e";
                    options.ClientSecret = "e6be78689cd05f802423ce807b818d015c53a0d36f9b167f138172b638815995";
                    options.CallbackPath = new PathString("/Privacy");
                    //options.AuthorizationEndpoint = "https://gitee.com/oauth/authorize";
                    //options.TokenEndpoint = "https://gitee.com/oauth/token";
                    //options.UserInformationEndpoint = "https://gitee.com/api/v5/user";
                    //options.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "id");
                    //options.ClaimActions.MapJsonKey(ClaimTypes.Name, "name");
                    //options.ClaimActions.MapJsonKey(ClaimTypes.Email, "email");
                    //options.SaveTokens = true; // 保存访问令牌和刷新令牌
                    //options.Scope.Add("projects");
                    //options.Scope.Add("user_info");

                    options.Events = new Microsoft.AspNetCore.Authentication.OAuth.OAuthEvents
                    {
                        OnCreatingTicket = context =>
                        {
                            var test = context.AccessToken;
                            return Task.CompletedTask;
                        }
                    };
                })
                //.AddOAuth("Gitee", "Demo Gitee", options => 
                //{
                //    options.ClientId = "43e21bdfe93a542a8af3e44396cbe39ef0c9318c4c0bc640c354a16a7372347e";
                //    options.ClientSecret = "e6be78689cd05f802423ce807b818d015c53a0d36f9b167f138172b638815995";
                //    options.CallbackPath = new PathString("/Privacy");
                //    options.AuthorizationEndpoint = "https://gitee.com/oauth/authorize";
                //    options.TokenEndpoint = "https://gitee.com/oauth/token";
                //    options.UserInformationEndpoint = "https://gitee.com/api/v5/user";
                //    options.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "id");
                //    options.ClaimActions.MapJsonKey(ClaimTypes.Name, "name");
                //    options.ClaimActions.MapJsonKey(ClaimTypes.Email, "email");
                //    options.SaveTokens = true; // 保存访问令牌和刷新令牌
                //    options.Scope.Add("projects");
                //    options.Scope.Add("user_info");

                //    options.Events = new Microsoft.AspNetCore.Authentication.OAuth.OAuthEvents
                //    {
                //        OnCreatingTicket = context => 
                //        {
                //            var test = context.AccessToken;
                //            return Task.CompletedTask;
                //        }
                //    };
                //})
                ;


var app = builder.Build();

// Configure the HTTP request pipeline.

app.UseStaticFiles();
app.UseRouting();

//启用身份认证服务
app.UseIdentityServer();
app.UseAuthentication();
app.UseAuthorization();

app.MapDefaultControllerRoute().RequireAuthorization(); 

app.Run();
